<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  formatDateTime,
  formatImageUrl,
  maskPhone,
  maskEmail
} from "@/utils/tools";
import { getUserAllOrderData, deleteOrder } from "@/api/order";
import { Search, View, Delete, Calendar } from "@element-plus/icons-vue";
import { Picture } from "@element-plus/icons-vue";
import { ElImageViewer } from "element-plus";

// 定义订单接口
interface OrderItem {
  id: string;
  orderNumber: string;
  status: number;
  description: string | null;
  goodsId?: string | null;
  storeId: string;
  storesName: string;
  name: string;
  pay: number;
  sourceId: number;
  productImage: string | null;
  productName: string | null;
  price: number;
  type: number; // 订单类型：0服饰、1活动、2周边
  createdTime: string;
  isRelease: number;
}

// 状态处理方法
const getStatusType = (status: number, type: number) => {
  // 根据订单类型返回不同的状态类型
  switch (type) {
    case 0: // 服装
      switch (status) {
        case 0:
          return "info"; // 已取消
        case 1:
          return "warning"; // 待拍摄
        case 2:
          return "primary"; // 进行中
        case 3:
          return "success"; // 已完成
        case 4:
          return "danger"; // 已超时
        default:
          return "info";
      }
    case 1: // 活动
      switch (status) {
        case 0:
          return "info"; // 已取消
        case 1:
          return "warning"; // 未开始
        case 2:
          return "primary"; // 进行中
        case 3:
          return "success"; // 已完成
        case 4:
          return "danger"; // 已超时
        default:
          return "info";
      }
    case 2: // 周边
      switch (status) {
        case 0:
          return "info"; // 已取消
        case 1:
          return "warning"; // 待取货
        case 2:
          return "success"; // 已取货
        case 3:
          return "danger"; // 已退款
        default:
          return "info";
      }
    default:
      return "info";
  }
};

const getStatusText = (status: number, type: number) => {
  // 根据订单类型返回不同的状态文本
  switch (type) {
    case 0: // 服装
      switch (status) {
        case 0:
          return "已取消";
        case 1:
          return "待拍摄";
        case 2:
          return "进行中";
        case 3:
          return "已完成";
        case 4:
          return "已超时";
        default:
          return "未知";
      }
    case 1: // 活动
      switch (status) {
        case 0:
          return "已取消";
        case 1:
          return "未开始";
        case 2:
          return "进行中";
        case 3:
          return "已完成";
        case 4:
          return "已超时";
        default:
          return "未知";
      }
    case 2: // 周边
      switch (status) {
        case 0:
          return "已取消";
        case 1:
          return "待取货";
        case 2:
          return "已取货";
        case 3:
          return "已退款";
        default:
          return "未知";
      }
    default:
      return "未知";
  }
};

// 获取订单类型文本
const getOrderTypeText = (type: number) => {
  switch (type) {
    case 0:
      return "服饰";
    case 1:
      return "活动";
    case 2:
      return "周边";
    default:
      return "未知";
  }
};

// 获取来源文本
const getSourceText = (sourceId: number) => {
  switch (sourceId) {
    case 2:
      return "抖音";
    case 3:
      return "小红书";
    case 4:
      return "美团";
    case 5:
      return "大众点评";
    case 6:
      return "自主进店";
    default:
      return "未知";
  }
};

// 查询表单
const orderFrom = ref({
  status: "",
  name: "",
  isRelease: "",
  userId: "",
  createdTime: "",
  message: "",
  pageNo: 1,
  pageSize: 10
});

// 表格数据
const tableData = ref<OrderItem[]>([]);
const total = ref(0);
const loading = ref(false);

// 状态选项
const statusOptions = [
  { label: "全部状态", value: "" },
  { label: "已取消", value: "0" },
  { label: "待拍摄", value: "1" },
  { label: "进行中", value: "2" },
  { label: "已完成", value: "3" },
  { label: "已超时", value: "4" }
];

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const res = await getUserAllOrderData(orderFrom.value);
    if (res.code === 200) {
      tableData.value = res.data.result;
      total.value = res.data.total;
      // 如果当前页没有数据且不是第一页，则回到上一页
      if (tableData.value.length === 0 && orderFrom.value.pageNo > 1) {
        orderFrom.value.pageNo--;
        await loadData();
      }
    } else {
      ElMessage.error(res.message || "获取订单列表失败");
    }
  } catch (error) {
    ElMessage.error("获取订单列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  orderFrom.value.pageNo = 1;
  orderFrom.value.message = orderFrom.value.name;
  loadData();
};

// 重置搜索
const handleReset = () => {
  orderFrom.value = {
    status: "",
    name: "",
    isRelease: "",
    userId: "",
    createdTime: "",
    message: "",
    pageNo: 1,
    pageSize: 10
  };
  loadData();
};

// 分页处理
const handleSizeChange = (val: number) => {
  orderFrom.value.pageSize = val;
  orderFrom.value.pageNo = 1;
  loadData();
};

const handleCurrentChange = (val: number) => {
  orderFrom.value.pageNo = val;
  loadData();
};

// 初始化
onMounted(() => {
  loadData();
});

// 搜索表单
const searchForm = reactive({
  keyword: "",
  status: "all",
  dateRange: [],
  paymentMethod: "all"
});

// 支付方式选项
const paymentOptions = [
  { label: "全部方式", value: "all" },
  { label: "微信支付", value: "wechat" },
  { label: "支付宝", value: "alipay" }
];

const detailDialogVisible = ref(false);
const currentOrder = ref<OrderItem | null>(null);

// 查看订单详情
const handleViewDetail = (row: OrderItem) => {
  currentOrder.value = row;
  detailDialogVisible.value = true;
};

// 取消订单
const handleCancel = row => {
  ElMessageBox.confirm("确定要取消该订单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      // TODO: 调用取消订单接口
      ElMessage.success("订单已取消");
      handleSearch();
    })
    .catch(() => {});
};

// 删除订单
const handleDelete = (row: OrderItem) => {
  ElMessageBox.confirm("确定要删除该订单吗？删除后不可恢复！", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        const res = await deleteOrder(row.id);
        if (res.code === 200) {
          ElMessage.success("删除成功");
          // 重置到第一页并重新加载数据
          orderFrom.value.pageNo = 1;
          await loadData();
        } else {
          ElMessage.error(res.message || "删除失败");
        }
      } catch (error: any) {
        ElMessage.error(error.message || "删除失败");
      }
    })
    .catch(() => {});
};

// 图片预览相关
const previewVisible = ref(false);
const previewImages = ref<string[]>([]);
const previewIndex = ref(0);

// 预览图片
const handlePreviewImage = (url: string | null) => {
  if (!url) return;

  const formattedUrl = formatImageUrl(url);
  previewImages.value = [formattedUrl];
  previewIndex.value = 0;
  previewVisible.value = true;
};

defineOptions({
  name: "Order"
});
</script>

<template>
  <div class="order-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="orderFrom" inline>
        <el-form-item label="订单状态" style="width: 250px">
          <el-select
            v-model="orderFrom.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input
            v-model="orderFrom.name"
            placeholder="请输入用户名/订单号"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        height="60vh"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="orderNumber" label="订单编号" min-width="180" />
        <el-table-column prop="name" label="用户名" width="120" />
        <el-table-column prop="storesName" label="店铺名称" min-width="150" />
        <el-table-column label="订单类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag type="info" effect="plain">
              {{ getOrderTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="来源" width="100" align="center">
          <template #default="{ row }">
            <el-tag type="success" effect="plain">
              {{ getSourceText(row.sourceId) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="商品信息" min-width="200">
          <template #default="{ row }">
            <div v-if="row.productName" class="product-info">
              <el-image
                :src="formatImageUrl(row.productImage)"
                class="product-image"
                fit="cover"
                @click="handlePreviewImage(row.productImage)"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="product-detail">
                <div class="name">{{ row.productName }}</div>
                <div class="price">¥{{ row.price.toFixed(2) }}</div>
              </div>
            </div>
            <div v-else class="appointment-info">
              <el-icon class="appointment-icon"><Calendar /></el-icon>
              <span class="appointment-text">到店预约</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status, row.type)">
              {{ getStatusText(row.status, row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createdTime"
          label="创建时间"
          width="180"
          align="center"
        >
          <template #default="{ row }">
            {{ formatDateTime(row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewDetail(row)">
              查看
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="orderFrom.pageNo"
          v-model:page-size="orderFrom.pageSize"
          :total="total"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="700px"
      destroy-on-close
    >
      <div v-if="currentOrder" class="order-detail">
        <div class="section">
          <h3 class="section-title">基本信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">订单号：</span>
              <span class="value">{{ currentOrder.orderNumber }}</span>
            </div>
            <div class="info-item">
              <span class="label">下单时间：</span>
              <span class="value">{{
                formatDateTime(currentOrder.createdTime)
              }}</span>
            </div>
            <div class="info-item">
              <span class="label">订单状态：</span>
              <span class="value">
                <el-tag
                  :type="getStatusType(currentOrder.status, currentOrder.type)"
                >
                  {{ getStatusText(currentOrder.status, currentOrder.type) }}
                </el-tag>
              </span>
            </div>
            <div class="info-item">
              <span class="label">店铺名称：</span>
              <span class="value">{{ currentOrder.storesName }}</span>
            </div>
            <div class="info-item">
              <span class="label">订单类型：</span>
              <span class="value">
                <el-tag type="info" effect="plain">
                  {{ getOrderTypeText(currentOrder.type) }}
                </el-tag>
              </span>
            </div>
            <div class="info-item">
              <span class="label">订单来源：</span>
              <span class="value">
                <el-tag type="success" effect="plain">
                  {{ getSourceText(currentOrder.sourceId) }}
                </el-tag>
              </span>
            </div>
          </div>
        </div>

        <div class="section">
          <h3 class="section-title">商品信息</h3>
          <div v-if="currentOrder.productName" class="product-info">
            <el-image
              :src="formatImageUrl(currentOrder.productImage)"
              :preview-src-list="
                currentOrder.productImage
                  ? [formatImageUrl(currentOrder.productImage)]
                  : []
              "
              class="product-image"
              fit="cover"
            />
            <div class="product-detail">
              <div class="name">{{ currentOrder.productName }}</div>
              <div class="description">
                {{ currentOrder.description || "-" }}
              </div>
              <div class="price">¥{{ currentOrder.price.toFixed(2) }}</div>
            </div>
          </div>
          <div v-else class="appointment-detail">
            <div class="appointment-header">
              <el-icon class="appointment-icon"><Calendar /></el-icon>
              <span class="appointment-title">到店预约</span>
            </div>
            <div class="appointment-info">
              <div class="info-row">
                <span class="label">预约店铺：</span>
                <span class="value">{{ currentOrder.storesName }}</span>
              </div>
              <div class="info-row">
                <span class="label">预约人：</span>
                <span class="value">{{ currentOrder.name }}</span>
              </div>
              <div v-if="currentOrder.description" class="info-row">
                <span class="label">备注信息：</span>
                <span class="value">{{ currentOrder.description || "-" }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 添加自定义图片预览组件 -->
    <el-image-viewer
      v-if="previewVisible"
      :url-list="previewImages"
      :initial-index="previewIndex"
      @close="previewVisible = false"
    />
  </div>
</template>

<style lang="scss" scoped>
.order-container {
  padding: 20px;
  background: var(--el-bg-color-page);

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .product-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .product-image {
        width: 50px;
        height: 50px;
        border-radius: 4px;
      }

      .product-detail {
        .name {
          font-size: 14px;
          margin-bottom: 4px;
        }

        .price {
          color: var(--el-color-danger);
          font-size: 13px;
        }
      }
    }

    .appointment-info {
      display: flex;
      align-items: center;
      gap: 8px;
      color: var(--el-color-primary);

      .appointment-icon {
        font-size: 18px;
      }

      .appointment-text {
        font-size: 14px;
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .order-detail {
    .section {
      margin-bottom: 24px;

      &:last-child {
        margin-bottom: 0;
      }

      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: var(--el-text-color-primary);
        margin: 0 0 16px;
        padding-bottom: 12px;
        border-bottom: 1px solid var(--el-border-color-lighter);
      }

      .info-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 16px;

        .info-item {
          .label {
            color: var(--el-text-color-secondary);
            margin-right: 8px;
          }

          .value {
            color: var(--el-text-color-primary);
          }
        }
      }

      .product-info {
        display: flex;
        gap: 16px;
        padding: 16px;
        background: var(--el-fill-color-light);
        border-radius: 8px;

        .product-image {
          width: 120px;
          height: 120px;
          border-radius: 4px;
        }

        .product-detail {
          flex: 1;

          .name {
            font-size: 16px;
            font-weight: 500;
            color: var(--el-text-color-primary);
            margin-bottom: 8px;
          }

          .description {
            font-size: 14px;
            color: var(--el-text-color-secondary);
            margin-bottom: 8px;
          }

          .price {
            font-size: 16px;
            color: var(--el-color-danger);
            font-weight: 500;
          }
        }
      }

      .appointment-detail {
        padding: 16px;
        background: var(--el-fill-color-light);
        border-radius: 8px;

        .appointment-header {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 16px;
          padding-bottom: 10px;
          border-bottom: 1px dashed var(--el-border-color-lighter);

          .appointment-icon {
            font-size: 20px;
            color: var(--el-color-primary);
          }

          .appointment-title {
            font-size: 16px;
            font-weight: 500;
            color: var(--el-color-primary);
          }
        }

        .appointment-info {
          .info-row {
            display: flex;
            margin-bottom: 12px;

            &:last-child {
              margin-bottom: 0;
            }

            .label {
              color: var(--el-text-color-secondary);
              min-width: 80px;
            }

            .value {
              color: var(--el-text-color-primary);
            }
          }
        }
      }

      .empty-product {
        text-align: center;
        padding: 32px;
        color: var(--el-text-color-secondary);
        background: var(--el-fill-color-light);
        border-radius: 8px;
      }
    }
  }
}
</style>
